package com.blinddate.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.blinddate.mapper.UserMapper;
import com.blinddate.pojo.entity.User;
import com.blinddate.pojo.entity.UserInf;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfWidgetAnnotation;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.util.List;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }

    public String pdf(UserInf userInf, String s) throws IOException {
        String font = "D:\\simsun.ttc,0";//字体路径
        String pdfmb = "2ad39b7c-f705-40d1-8ebc-58fc18ac8e9e.pdf";//模板url路径
        String localpdf=userInf.getId()+".pdf";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 下载模板文件到本地
        InputStream templateInputStream = ossClient.getObject(bucketName, pdfmb).getObjectContent();
        File templateFile = new File("local_template.pdf");
        OutputStream templateOutputStream = null;
        templateOutputStream = new FileOutputStream(templateFile);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = templateInputStream.read(buffer)) != -1) {
            templateOutputStream.write(buffer, 0, bytesRead);
        }
        templateInputStream.close();
        templateOutputStream.close();
        PdfDocument pdfDocument = new PdfDocument(new PdfReader(templateFile), new PdfWriter(localpdf));
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDocument, false);
        PdfFont Font = PdfFontFactory.createFont(font);
        DeviceRgb color = new DeviceRgb(0, 0, 0);
        //文本填充
        form.getFormFields().get("name").setValue(userInf.getName()).setColor(color).setFont(Font);
        form.getFormFields().get("age").setValue(userInf.getAge().toString()).setColor(color).setFont(Font);
        form.getFormFields().get("habitation").setValue(userInf.getHabitation()).setColor(color).setFont(Font);
        form.getFormFields().get("height").setValue(userInf.getHeight().toString()).setColor(color).setFont(Font);
        form.getFormFields().get("phone").setValue(userInf.getPhone()).setColor(color).setFont(Font);
        form.getFormFields().get("education").setValue(userInf.getEducation()).setColor(color).setFont(Font);
        form.getFormFields().get("gender").setValue(userInf.getGender().toString()).setColor(color).setFont(Font);
        form.getFormFields().get("income").setValue(userInf.getIncome().toString()).setColor(color).setFont(Font);
        form.getFormFields().get("career").setValue(userInf.getCareer()).setColor(color).setFont(Font);
        form.getFormFields().get("home").setValue(userInf.getHome()).setColor(color).setFont(Font);
        form.getFormFields().get("real_estate").setValue(userInf.getRealEstate()).setColor(color).setFont(Font);
        form.getFormFields().get("vehicle").setValue(userInf.getVehicle()).setColor(color).setFont(Font);
        form.getFormFields().get("nation").setValue(userInf.getNation()).setColor(color).setFont(Font);
        form.getFormFields().get("shape").setValue(userInf.getShape()).setColor(color).setFont(Font);
        form.getFormFields().get("marriage").setValue(userInf.getMarriage()).setColor(color).setFont(Font);
        form.getFormFields().get("marry").setValue(userInf.getMarry()).setColor(color).setFont(Font);
        form.getFormFields().get("select_age").setValue(userInf.getSelectAge().toString()).setColor(color).setFont(Font);
        form.getFormFields().get("select_education").setValue(userInf.getSelectEducation()).setColor(color).setFont(Font);
        form.getFormFields().get("select_height").setValue(userInf.getSelectHeight().toString()).setColor(color).setFont(Font);
        form.getFormFields().get("self_intro").setValue(userInf.getSelfIntro()).setColor(color).setFont(Font);
        //填充图片
        PdfFormField formField= form.getField("image");
        List<PdfWidgetAnnotation> widgets=formField.getWidgets();
        PdfWidgetAnnotation widget=widgets.get(0);
        //域左下角顶点坐标
        float x1=widget.getRectangle().getAsNumber(0).floatValue();
        float y1=widget.getRectangle().getAsNumber(1).floatValue();
        //域右上角顶点坐标
        float x2=widget.getRectangle().getAsNumber(2).floatValue();
        float y2=widget.getRectangle().getAsNumber(3).floatValue();
        //域宽高
        float fieldWidth=x2-x1;
        float fieldHeight=y2-y1;
        //创建图片对象
        Image im=new Image(ImageDataFactory.create(userInf.getImgSrc()));
        Image image=im.scaleToFit(fieldWidth,fieldHeight);//图片自适应缩放
        //获取图片的自适应缩放后的宽高
        float scaleWidth=image.getImageScaledWidth();
        float scaleHeight=image.getImageScaledHeight();
        //计算图片居中位置
        float centerX=x1+(fieldWidth/2)-(scaleWidth/2);
        float centerY=y1+(fieldHeight/2)-(scaleHeight/2);
        image.setFixedPosition(centerX,centerY);
        //获取文档对象 将图像添加
        Document document=new Document(pdfDocument);
        document.add(image);
        form.flattenFields();
        document.close();
        pdfDocument.close();
        InputStream resultInputStream = new FileInputStream(localpdf);
        ossClient.putObject(bucketName, s, resultInputStream);
        resultInputStream.close();

        // 删除本地文件
        templateFile.delete();
        new File(localpdf).delete();

        // 关闭 OSS 客户端
        ossClient.shutdown();
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(s);
        String path=stringBuilder.toString();
        log.info("pdf文件上传到:{}", path);
        return path;
    }
}

